angular.module('employee.controllers', [])
// 员工列表
.controller('EmployeesCtrl', function($scope) {
	var usersSubHandle = $scope.subscribe('users');
	var companySubHandle = $scope.subscribe('companies');

	$scope.listCanSwipe = true;
	$scope.$on('$ionicView.enter', function(e) {

		$scope.helpers({
			company:function(){
				return Companies.findOne({},{fields:{users_num:1}});
			},
			sysUserCount:function(){
				return Meteor.users.find({'state':{'$nin':['未启用','已停用']}}).count();
			},
			employees:function(){
				return Meteor.users.find({'state':{'$not':'已停用'}},{fields:{
					'_id':1,'username':1,'profile.name':1,'profile.sex':1,'profile.departments':1,
					'profile.phones':1,'profile.roleName':1,'profile.state':1}});
			}
		});
	});
	$scope.makeCall = function(employee){
		var number = employee.profile.phones[0].number || employee.profile.phones[1].number;
		document.location.href = 'tel:'+number;
	};
})
// 员工信息
.controller('EmployeeCtrl', function($scope,$rootScope,$stateParams,$location,$ionicPopover,$ionicPopup,ToastService) {
	var usersSubHandle = $scope.subscribe('users');
	$scope.$on('$ionicView.enter', function(e) {
		$scope.helpers({
			theUser: function() {
			  return Meteor.users.findOne({_id:$stateParams._id});
			}
		});
	});

	// 隐藏详细信息
	$scope.isBlockShown=true;
	$scope.toggleFeilds = function(){
		$scope.isBlockShown = !$scope.isBlockShown;
	};

  	// 顶部更多信息按钮
	$scope.eRouter = function(event){
		if($rootScope.isEdit){
			$rootScope.toggleEdit();
		}else{
			$scope.openPopover(event);
		}
	};
	$ionicPopover.fromTemplateUrl('templates/employee/popover.html', {
		scope: $scope
	}).then(function(popover) {
		$scope.popover = popover;
	});

	$scope.openPopover = function($event) {
		$scope.popover.show($event);
	};
	$scope.closePopover = function() {
		$scope.popover.hide();
	};
	$scope.$on('$destroy', function() {
		$scope.popover.remove();
	});
	$scope.$on('popover.hidden', function() {
	});
	$scope.$on('popover.removed', function() {
	});

	$scope.update = function(){
		if ($scope.theUser === {}) return;
		Meteor.call('updateUser', $scope.theUser, function(error){
          if (error) {
            console.log(error);
          }else {
          	 ToastService.show('成功更新员工信息');
          }
        });
	};

	// 重置用户密码
	$scope.resetUserPw = function(){
		$scope.pwData = {};
		var myPopup = $ionicPopup.show({
			template: '<input type="password" ng-model="pwData.password" class="input-border-bottom" placeholder="新密码">'+
			'<p><br>注意：该用户将被强制登出易联锁！</p>'+
			'<p ng-show="pwData.password.length<6" class="assertive">密码必须大于6位<p>',
			title: '重置该用户密码',
			scope: $scope,
			buttons: [
				{ text: '取消' },
				{ text: '确定',type: 'button-royal',
					onTap: function(e) {
					  if (!$scope.pwData.password || $scope.pwData.password.length<6) {
					  	$scope.pwData.pwLength = true;
						//未填时不允许确认
						e.preventDefault();
					  } else {
					  	$scope.pwData.pwLength = false;
					  	$scope.pwData._id = $scope.theUser._id;
						//向服务器提交修改 TODO
						Meteor.call('resetUserPw', $scope.pwData, function(error){
				          if (error) {
				            console.log(error);
				          }else {
				          	ToastService.show('成功重置员工密码');
				          }
				        });
					  }
					}
				}
			]
		});
	};

	// 更改员工在职状态
	$scope.updateEmployeeState = function(){
		$scope.employee={
			state : $scope.theUser.profile.state
		};
		var myPopup = $ionicPopup.show({
			template: '<ion-list>'+
					    '<ion-radio ng-model="employee.state" ng-value="\'在职\'">在职</ion-radio>'+
					    '<ion-radio ng-model="employee.state" ng-value="\'休假中\'">休假中</ion-radio>'+
					    '<ion-radio ng-model="employee.state" ng-value="\'离职\'">离职</ion-radio>'+
					  '</ion-list>',
			cssClass: 'popup-radio',
			title: '更改员工在职状态',
			scope: $scope,
			buttons: [
				{ text: '取消' },
				{ text: '确定',type: 'button-royal',
					onTap: function(e) {
						console.log($scope.employee.state);
						var data = {
							uid:$scope.theUser._id,
							state:$scope.employee.state
						};
						if ($scope.employee.state==$scope.theUser.profile.state) {
							$scope.employee=null;
							return;
						} else {
							Meteor.call('updateEmployeeState', data, function(error){
								if (error) {
									console.log(error);
								}else {
									ToastService.show('成功更新员工状态');
								}
							});
						}
					}
				}
			]
		});
	};

	$scope.switchUser = function(){
		var stateOpt = $scope.theUser.state=='已启用'?'已停用':'已启用';
		Meteor.call('switchUser', $scope.theUser._id, function(error){
          if (error) {
            console.log(error);
          }else {
          	ToastService.show(stateOpt+'员工账号');
          }
        });
	};

	//拨打电话
	$scope.callEmployee = function(){
		var number = $scope.theEmployee.phones[0].number || $scope.theEmployee.phones[1].number;
		$location.href = 'tel:'+number;
	};

})

.controller('EmployeeAddCtrl',function($scope,$state,$ionicModal,$timeout,deptService,ToastService){

	var deptsSubHandle = $scope.subscribe('departments');
	var optionsSubHandle = $scope.subscribe('default_options');

	$scope.helpers({
		departments: function() {
		  return Departments.find({});
		},
		roles: function() {
		  return DefaultOptions.findOne({name:'职能'},{'value_set':1});
		}
	});
	$scope.autorun(function(){
		if(deptsSubHandle.ready()){
			$scope.deptTree = deptService.getCatTree();
   			deptService.expendAll($scope.deptTree);
		}
	});

	$ionicModal.fromTemplateUrl('templates/employee/select-department.html', {
		scope: $scope,
		animation: 'slide-in-up'
	}).then(function(modal) {
		$scope.modal = modal;
	});
	$scope.openModal = function() {
		$scope.modal.show();
	};
	$scope.closeModal = function() {
		$scope.modal.hide();
	};
	$scope.$on('$destroy', function() {
		$scope.modal.remove();
	});
	$scope.$on('modal.hidden', function() {
	});
	$scope.$on('modal.removed', function() {
	});


	$scope.newEmployee={
		emails:[],
		profile:{
			phones:[{label:'工作'},{label:'备用'}]
		}
	};

	$scope.select = function(item){
		// 有父级部门
		if(item.parents && item.parents.length){
			$scope.newEmployee.profile.departments = Departments.find({_id:{'$in':item.parents}},{fields:{_id:1,type:1,name:1}}).fetch();
			$scope.newEmployee.profile.departments.push({'_id':item._id,'type':item.type,'name':item.name});
		// 没有父级部门
		}else{
			$scope.newEmployee.profile.departments=[{'_id':item._id,'type':item.type,'name':item.name}];
		}
		$timeout(function(){
            $scope.closeModal();
        },300);
	};

	$scope.isSysUser = true;
	$scope.add = function(){
		// 姓名电话未填 禁止提交
		if (!$scope.newEmployee.profile.name || !$scope.newEmployee.profile.phones[0].number) return;

		$scope.newEmployee.profile.departments.forEach(function(e){
        	e.$$hashKey=undefined;
        });

		$scope.newEmployee.username=$scope.newEmployee.profile.phones[0].number.trim();
		switch($scope.newEmployee.profile.state){
			case '在职':
				$scope.newEmployee.state=$scope.isSysUser?'已启用':'未启用';
				break;
			case '休假中':
				$scope.newEmployee.state=$scope.isSysUser?'锁定中':'未启用';
				break;
			case '离职':
				$scope.newEmployee.state=$scope.isSysUser?'已停用':'未启用';
				break;
		}


		console.log($scope.newEmployee);
		//回调服务器端插入方法
		Meteor.call('addUser', $scope.newEmployee, function(error){
          if (error) {
          	ToastService.show(error);
            console.log(error);
          }
          else {
          	ToastService.show('成功更新员工信息');
			$state.go('app.employees');

          }
        });
	};
});
